/*
   file : api.c
   University of Jiangsu
   memoryDB      2010.6
 */


#include"api.h"
/*
   链接服务端函数,成功返回套接字
 */
int sql_connect(char *ip,int port)
{
	int sockfd;
	struct sockaddr_in serveradd;

	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0)
	  return -1;

	bzero(&serveradd,sizeof(serveradd));
	serveradd.sin_family=AF_INET;
	serveradd.sin_port=htons(port);

	if(inet_pton(AF_INET,ip,&serveradd.sin_addr) <=0 )
	  return -2;

	if(connect(sockfd,(struct sockaddr *)&serveradd,sizeof(serveradd)) < 0)
	  return -3;

	return sockfd;
} 

/*
   SQL语句执行函数
 */
int sql_exec(char *sql,int len,int sockfd)
{
	if(!strcmp(sql,"bye;"))
		return -2;
	write(sockfd,sql,len);

	int n,flag=0;
	char receive[MAX_COMMAND];
	while(1){
		bzero(receive,MAX_COMMAND);
		n=read(sockfd,receive,MAX_COMMAND);
		if(n==0)
			return -1;	
		if(receive[strlen(receive)-1]=='\n'&&receive[strlen(receive)-2]=='\n'&&receive[strlen(receive)-3]=='\n'){	
			receive[strlen(receive)-3]='\0';
			flag=1;
		}
		printf("%s",receive);
		if(flag)
		  break;
	}
	return 0;
}
